package com.example.traffic_learning;

import global.AsyncResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import DTO.SignDTO;
import DTO.SignTypeDTO;
import adapter.GridAdapterTrafficSignSystem;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class FragTrafficSignSystem extends Fragment implements AsyncResponse{
	ArrayList<SignTypeDTO> arrSignTypeDTO = new ArrayList<SignTypeDTO>();
	ArrayList<SignDTO> arrSignDTO = new ArrayList<SignDTO>();
	AlertDialog alertDialog = null;
	AlertDialog.Builder alertDialogBuilder;
	LinearLayout myLayout;
	View view1;
	ExpandableHeightGridView grid;
	
	private GetSignDatabaseTask databaseTask;
	private AsyncResponse asyncResponse = null;
	private List<String> listTypeName = new ArrayList<String>();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		asyncResponse = this;
		final View view = inflater.inflate(R.layout.activity_traffic_sign_system, container, false);
		view1 = inflater.inflate(R.layout.custom_dialog_sign, container, false);
		final ImageView imageSearch = (ImageView)view.findViewById(R.id.image_search);
		final EditText editTextSearch = (EditText)view.findViewById(R.id.text_search);
		
		arrSignTypeDTO = SignTypeDTO.getAllSignTypeDTO(getActivity());
		databaseTask = new GetSignDatabaseTask(getActivity());
		//databaseTask.delegate = asyncResponse;
		//databaseTask.execute("","Tất cả");
		//arrSignDTO = SignDTO.GetSignsByKeyWord(getActivity(), editTextSearch.getText().toString(), "Tất cả");
		
		myLayout = (LinearLayout)view.findViewById(R.id.layout_show_sign);
		
		final Spinner spinnerSignType = (Spinner)view.findViewById(R.id.spinner_sign_type);
		final List<String> list = new ArrayList<String>();
		list.add("Tất cả");
		for(SignTypeDTO signTypeDTO : arrSignTypeDTO){
			list.add(signTypeDTO.getName());
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, list);
		dataAdapter.setDropDownViewResource(R.layout.spinner_item);
		spinnerSignType.setAdapter(dataAdapter);
		spinnerSignType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> list, View arg1,
					int pos, long arg3) {
				while(arrSignDTO.size() > 0){
					arrSignDTO.remove(0);
				}
				editTextSearch.setText("");
				if(list.getItemAtPosition(pos).toString().equals("Tất cả")){
					if(databaseTask != null){
						databaseTask.cancel(true);
						databaseTask = new GetSignDatabaseTask(getActivity());
		   				databaseTask.delegate = asyncResponse;
		   				databaseTask.execute("","Tất cả");
					}
					//arrSignDTO = SignDTO.getAllSignDTOBySignType(getActivity(), "Tất cả");
				}else{
					if(databaseTask != null){
						databaseTask.cancel(true);
						databaseTask = new GetSignDatabaseTask(getActivity());
		   				databaseTask.delegate = asyncResponse;
		   				databaseTask.execute("",arrSignTypeDTO.get(pos - 1).getID());
					}
					//arrSignDTO = SignDTO.getAllSignDTOBySignType(getActivity(), arrSignTypeDTO.get(pos - 1).getID());
				}
				//loadSignTraffic(arrSignDTO, myLayout, view1);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
					
				
			}
		});
		
		editTextSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				imageSearch.setVisibility(View.INVISIBLE);
		   		if(editTextSearch.getText().length() == 0){
		   			imageSearch.setVisibility(View.VISIBLE);
		   		}else{
		   			while(arrSignDTO.size() > 0){
		   				arrSignDTO.remove(0);
		   			}
		   			if(spinnerSignType.getItemAtPosition(spinnerSignType.getSelectedItemPosition()).toString().equals("Tất cả")){
		   				if(databaseTask != null){
							databaseTask.cancel(true);
							databaseTask = new GetSignDatabaseTask(getActivity());
			   				databaseTask.delegate = asyncResponse;
			   				databaseTask.execute(editTextSearch.getText().toString(), "Tất cả");
						}
		   				//arrSignDTO = SignDTO.GetSignsByKeyWord(getActivity(), editTextSearch.getText().toString(), "Tất cả");
					}else{
						if(databaseTask != null){
							databaseTask.cancel(true);
							databaseTask = new GetSignDatabaseTask(getActivity());
			   				databaseTask.delegate = asyncResponse;
			   				databaseTask.execute(editTextSearch.getText().toString(), arrSignTypeDTO.get(spinnerSignType.getSelectedItemPosition() - 1).getID());
						}
						//arrSignDTO = SignDTO.GetSignsByKeyWord(getActivity(), editTextSearch.getText().toString(), arrSignTypeDTO.get(spinnerSignType.getSelectedItemPosition() - 1).getID());
					}
		   			//loadSignTraffic(arrSignDTO, myLayout, view1);
		   		}
			}
		});
		return view;
	}
	private int dpToPx(int dp) {
	    DisplayMetrics displayMetrics = getActivity().getBaseContext().getResources().getDisplayMetrics();
	    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
	    return px;
	}
	public int pxToDp(int px) {
	    DisplayMetrics displayMetrics = getActivity().getBaseContext().getResources().getDisplayMetrics();
	    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
	    return dp;
	}
	private void loadSignTraffic(ArrayList<SignDTO> list, LinearLayout myLayout, final View view1){
		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
		if(((LinearLayout) myLayout).getChildCount() > 0) 
		    ((LinearLayout) myLayout).removeAllViews();
		while(listTypeName.size() > 0){
			listTypeName.remove(0);
		}
		for(int i = 0; i < list.size(); i++){
			if(!listTypeName.contains(list.get(i).getTypeName())){
				listTypeName.add(list.get(i).getTypeName());
			}
		}
		for(int i = 0; i < listTypeName.size(); i++){
			final ArrayList<SignDTO> temp = new ArrayList<SignDTO>();
			for(int j = 0; j < list.size(); j++){
				if(listTypeName.get(i).equals(list.get(j).getTypeName())){
					temp.add(list.get(j));
				}
			}
			grid = new ExpandableHeightGridView(getActivity().getBaseContext());
			TextView textView = new TextView(getActivity());
			//TODO
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
																	LinearLayout.LayoutParams.WRAP_CONTENT);
			textView.setLayoutParams(layoutParams);
			textView.setText(Html.fromHtml("<strong>" + capitalize(listTypeName.get(i)) + "</strong>"));
			//textView.setBackgroundResource(R.drawable.banner);
			//textView.setTextColor(Color.WHITE);
			textView.setTextSize(18);
			textView.setPadding(dpToPx(30), 0, 0, 0);
			//textView.setGravity(Gravity.CENTER_VERTICAL);
			myLayout.addView(textView);
			myLayout.addView(grid);
			myLayout.setGravity(Gravity.CENTER_VERTICAL);
			grid.setNumColumns(3);
			switch(metrics.densityDpi){
			case DisplayMetrics.DENSITY_XHIGH:
				grid.setColumnWidth(dpToPx(100));
				break;
			case DisplayMetrics.DENSITY_XXHIGH:
				grid.setColumnWidth(dpToPx(100));
				break;
			case DisplayMetrics.DENSITY_LOW:
				grid.setColumnWidth(dpToPx(90));
				break;
			default:
				grid.setColumnWidth(dpToPx(90));
				break;	
			}
			grid.setPadding(dpToPx(20), dpToPx(20), dpToPx(20), dpToPx(20));
			grid.setStretchMode(grid.getColumnWidth());
			grid.setScrollContainer(false);
			grid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
			grid.setGravity(Gravity.CENTER_VERTICAL);
			grid.setAdapter(new GridAdapterTrafficSignSystem(getActivity(), temp));
			grid.setExpanded(true);
			grid.setScrollbarFadingEnabled(false);
			grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
						long arg3) {
					alertDialogBuilder = new AlertDialog.Builder(getActivity());
					
					alertDialogBuilder.setCancelable(false)
							   .setPositiveButton("Trở về", new DialogInterface.OnClickListener() {
								
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
							   });
					TextView textNameSign = (TextView)view1.findViewById(R.id.text_show_name_sign);
					textNameSign.setText(Html.fromHtml( "<strong>Tên</strong>" + "\t\t\t\t\t <strong>:</strong>\t" + temp.get(pos).getName()));
					TextView textNumber = (TextView)view1.findViewById(R.id.text_number_sign);
					textNumber.setText(Html.fromHtml("<strong>Số hiệu</strong>" + "\t\t\t <strong>:</strong>\t" + temp.get(pos).getNumber()));
					
					TextView textContent = (TextView)view1.findViewById(R.id.text_sign_detail);
					textContent.setText(Html.fromHtml("<strong>Nội dung</strong>" + "\t\t <strong>:</strong>\t" + temp.get(pos).getContent()));
					
					TextView textType = (TextView)view1.findViewById(R.id.text_type_sign);
					textType.setText(Html.fromHtml("<strong>Loại</strong>" + "\t\t\t\t\t <strong>:</strong>\t" + temp.get(pos).getTypeName()));
					Drawable imageDrawable = null;
					try {
						Options opts = new BitmapFactory.Options();
						opts.inDensity = DisplayMetrics.DENSITY_LOW;
						imageDrawable = Drawable.createFromResourceStream(getResources(), null, getActivity().getAssets().open(temp.get(pos).getImagePath()), null, opts);
					} catch (IOException e) {
						e.printStackTrace();
					}
					ImageView image = (ImageView)view1.findViewById(R.id.image_view_sign_detail);
					image.setImageDrawable(imageDrawable);
					
					LinearLayout myLayout = (LinearLayout)view1.findViewById(R.id.layout_sign_content);
					try{
						alertDialogBuilder.setView(myLayout);
					}catch(Exception e){}
					if(alertDialog == null)
						alertDialog = alertDialogBuilder.create();
					alertDialog.show();
					
				}
			});
		}
	}
	private String capitalize(String source){
		source = source.toLowerCase();
		String[] words = source.split(" ");
		source = "";
		for(int i = 0; i < words.length; i++){
			if(i < words.length - 1){
				source += Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1) + " ";
			}else{
				source += Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1);
			}
				
		}
		return source;
	}
	@Override
	public void processGetDatabaseFinish(String output) {
		
	}
	@Override
	public void processConvertTextFinish(Spanned ouput, int index) {
		
	}
	@Override
	public void processGetSignDatabaseFinish(ArrayList<SignDTO> arrayDTO) {
		arrSignDTO = arrayDTO;
		loadSignTraffic(arrSignDTO, myLayout, view1);		
	}
	@Override
	public void processGetFineDatabaseFinish(String output) {
		
	}
}
